package com.arsn.myf.common.util.result;

import com.arsn.myf.common.enums.ResultCode;
import lombok.Data;
import java.io.Serializable;

/**
 * 返回数据模板
 * @author zhongrj
 * @time 2021-9-10
 */
@Data
public class R<T> implements Serializable {
    private static final long serialVersionUID = 8161098857984868711L;

    /**
     * 返回状态码
     */
    private int code;

    /**
     *是否成功
     */
    private boolean success;

    /**
     * 数据
     */
    private T data;

    /**
     * 消息
     */
    private String msg;


    public R(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public R(String msg) {
        this.msg = msg;
    }

    public R(int code, String msg,boolean success) {
        this.code = code;
        this.msg = msg;
        this.success = success;
    }

    public R(int code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }

    /**
     * 返回数据
     * @param data
     * @param <T>
     * @return
     */
    public static <T> R<T> data(T data){
        return data(data,"操作成功");
    }

    public static <T> R<T> data(T data, String msg){
        return data(200,data,msg);
    }

    public static <T> R<T> data(int code, T data, String msg){
        return new R(code,data,data==null?"暂无承载数据":msg);
    }


    /**
     * error 消息
     * @param code
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> R<T> error(int code, String msg){
        return new R(code,msg);
    }

    public static <T> R<T> error(String msg){
        return new R(500,msg);
    }




    /**
     * 异常返回
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> R<T> errorException(String msg){
        return new R(500,msg);
    }

    public static <T> R<T> errorException(ResultCode resultCode){
        return new R(resultCode.getCode(),resultCode.getMsg());
    }


    /**
     * 返回状态
     * @param <T>
     * @return
     */
    public static <T> R<T> status(boolean flag){
        return flag ? success("操作成功",flag) : fail("操作失败",flag);
    }


    public static <T> R<T> success(String msg, boolean success){
        return new R(200,msg,success);
    }


    public static <T> R<T> fail(String msg, boolean success){
        return new R(400,msg,success);
    }
}
